package com.list.fans.controller;

import com.list.fans.common.Constant;
import com.list.fans.common.JsonResult;
import com.list.fans.model.Photo;
import com.list.fans.model.User;
import com.list.fans.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class UserController {
    @Autowired
    UserService userService;

    private static Logger logger = LoggerFactory.getLogger(PostController.class);

    /**
     * 用户登录
     * 传入参数 account 用户手机号或邮箱   userPassword 登录密码
     * 传出参数 User的所有字段
     * 接口 /user/login
     * @param account
     * @param userPassword
     * @return
     */
    @RequestMapping("/user/login")
    @ResponseBody
    public Object userLogin(String account, String userPassword, HttpServletRequest request){
        JsonResult result = null;
        try{
            User user=userService.userLogin(account,userPassword);
            logger.info("传入参数：account:{}    userPassword:{}",account,userPassword);
            if(user!=null){
                result = new JsonResult("登录成功",Constant.STATUC_SUCCESS,user);
                request.getSession().setAttribute("loginUser",user);
                logger.info("Session存储：loginUser:{}", request.getSession().getAttribute("loginUser"));
            }else{
                result = new JsonResult("用户名或密码错误",Constant.STATUC_UNFOUND);
            }
        }catch(Exception e){
            logger.info("错误信息：{}",e.getMessage());
            result = new JsonResult("登录异常",Constant.STATUC_FAILURE);
        }
        return result;
    }

    /**
     * 修改密码（密码验证）
     * 传入参数 oldPassword 原密码   newPassword 新密码
     * 传出参数 User的所有字段
     * 接口 /updata/user/password
     * @param oldPassword
     * @param newPassword
     * @param request
     * @return
     */
    @RequestMapping("/updata/user/password")
    @ResponseBody
    public Object updateUserPassword(String oldPassword, String newPassword, HttpServletRequest request){
        User loginUser=(User)request.getSession().getAttribute("loginUser");
        JsonResult result = null;
        if(oldPassword.equals(loginUser.getUserPassword())){
            try{
                logger.info("传入参数：UserId:{}    userPassword:{}",loginUser.getUserId(),newPassword);
                User user=userService.updateUserPassword(loginUser.getUserId(),newPassword);
                if(newPassword.equals(user.getUserPassword())){
                    result = new JsonResult(Constant.STATUC_SUCCESS,"修改成功",user);
                    request.getSession().setAttribute("loginUser",user);
                    logger.info("修改Session存储：loginUser:{}",user);
                }else{
                    result = new JsonResult(Constant.STATUC_UNFOUND,"修改失败");
                }
            }catch (Exception e){
                logger.info("错误信息：{}",e.getMessage());
                result = new JsonResult(Constant.STATUC_FAILURE,"修改异常");
            }
        }else{
            result = new JsonResult(Constant.STATUC_UNFOUND,"原密码错误");
        }
        return result;
    }

    /**
     * 修改密码（短信验证）
     * 传入参数 code 短信验证码   newPassword 新密码
     * 传出参数 User的所有字段
     * 接口 /updata/user/password/forget
     * @param code
     * @param newPassword
     * @param request
     * @return
     */
    @RequestMapping("/updata/user/password/forget")
    @ResponseBody
    public Object updateUserPasswordForget(String code, String newPassword, HttpServletRequest request){
        User loginUser=(User)request.getSession().getAttribute("loginUser");
        JsonResult result = null;
        //if(code.equals(String.valueOf(request.getSession().getAttribute("code")))){
            try{
                logger.info("传入参数：UserId:{}    userPassword:{}",loginUser.getUserId(),newPassword);
                User user=userService.updateUserPassword(loginUser.getUserId(),newPassword);
                if(newPassword.equals(user.getUserPassword())){
                    result = new JsonResult("修改成功",Constant.STATUC_SUCCESS,user);
                    request.getSession().setAttribute("loginUser",user);
                    logger.info("修改Session存储：loginUser:{}",user);
                }else{
                    result = new JsonResult("修改失败",Constant.STATUC_UNFOUND);
                }
            }catch (Exception e){
                logger.info("错误信息：{}",e.getMessage());
                result = new JsonResult("修改异常",Constant.STATUC_FAILURE);
            }
//        }else{
//            result = new JsonResult("验证码错误",Constant.STATUC_UNFOUND);
//        }
        return result;
    }
    /**
     * 注册用户
     * 传入参数  User对象 userName , userPassword , userSex , userBirth , userHeadshot , userEmail , userTelephone , userMotto
     * 传出参数    无
     * 接口 /insert/user
     * @param user
     * @return
     */
    @RequestMapping("/insert/user")
    @ResponseBody
    public Object insertUser(User user, Photo photo){
        JsonResult result = null;
        //验证用户名是否重复
        try{
            User u1=userService.selectUserNameIsOk(user.getUserName());
            System.out.println(user.getUserName()+"============"+u1.getUserName());
            if(u1!=null){
                result = new JsonResult("用户名已注册",Constant.STATUC_FAILURE);
                return result;
            }
        }catch (Exception e){
            logger.info("错误信息：{}",e.getMessage());
            result = new JsonResult("验证用户名是否重复异常",Constant.STATUC_FAILURE);
        }
        //验证手机号是否重复
        try{
            User u2=userService.selectUserTelephoneIsOk(user.getUserTelephone());
            if(u2!=null){
                result = new JsonResult("手机号已注册",Constant.STATUC_FAILURE);
                return result;
            }
        }catch (Exception e){
            logger.info("错误信息：{}",e.getMessage());
            result = new JsonResult("验证手机号是否重复异常",Constant.STATUC_FAILURE);
        }
        //验证邮箱是否重复
        try{
            User u3=userService.selectUserEmailIsOk(user.getUserEmail());
            if(u3!=null){
                result = new JsonResult("邮箱已注册",Constant.STATUC_FAILURE);
                return result;
            }
        }catch (Exception e){
            logger.info("错误信息：{}",e.getMessage());
            result = new JsonResult("验证邮箱是否重复异常",Constant.STATUC_FAILURE);
        }
        //注册
        try{
            int i=userService.insertUser(user);

            result = new JsonResult("注册成功",Constant.STATUC_SUCCESS);

        }catch (Exception e){
            logger.info("错误信息：{}",e.getMessage());
            result = new JsonResult("注册异常",Constant.STATUC_FAILURE);
        }
        return result;
    }


    /**
     * 根据用户id查询用户详细信息@xyb
     * 传入参数userid
     * 接口/select/user/message
     * 请求类型post
     * @param userid
     * @return
     */
    @RequestMapping(value = "/select/user/message",method = RequestMethod.POST)
    @ResponseBody
    public JsonResult select(
            @RequestParam(value = "userId",defaultValue = "",required = false)String userid
    ){
        JsonResult result=null;
        try{
            User user=userService.selectUserMessage(userid);
            System.out.println(user.getUserSex());
            if (user!=null){
                logger.info("参数：",userid);
                result=new JsonResult("查询成功","200",user);
            }else {
                result=new JsonResult("查询失败","404");
            }
        }catch (Exception ex){
            logger.info(ex.getMessage());
            result=new JsonResult("出错了","500");
        }
        return  result;
    }

    /**
     * 根据用户id修改用户头像@xyb
     * 传入参数userid
     * 接口/update/user/photo
     * 请求类型post
     * @param userid
     * @param photo
     * @return
     */
    @RequestMapping(value = "/update/user/photo",method = RequestMethod.POST)
    @ResponseBody
    public  JsonResult updateUserPhoto(
            @RequestParam(value = "userid",defaultValue = "",required = false)String userid,
            @RequestParam(value = "photo",defaultValue = "",required = false)String photo){
        JsonResult result=null;
        try{
            userService.updateUserPhoto(photo,userid);
            logger.info("参数{}",userid);
            result=new JsonResult("查询成功","200");
        }catch (Exception ex){
            logger.info(ex.getMessage());
            result=new JsonResult("出错了","500");
        }
        return result;
    }

    /**
     * 根据用户id修改用户密码@xyb
     * 传入参数userid
     * 接口/update/user/password
     * 请求类型post
     * @param password
     * @param userid
     * @return
     */
//    @RequestMapping(value = "/update/user/password",method = RequestMethod.POST)
//    @ResponseBody
//    public  JsonResult  updateUserPassword(
//            @RequestParam(value = "password",defaultValue = "",required = false)String password,
//            @RequestParam(value = "userid",defaultValue = "",required = false) String userid){
//        JsonResult result=null;
//        try{
//            userService.updateUserPassword(password,userid);
//            logger.info("参数{}",userid);
//            result=new JsonResult("查询成功","200");
//        }catch (Exception ex){
//            result=new JsonResult("出错了","500");
//        }
//        return result;
//    }

    /**
     * 根据用户id修改用户个人信息@xyb
     * 可修改：用户名，性别，生日，邮箱，电话，签名\头像
     *  传入参数：userName、userSex、userBirth、userEmail、userTelephone、userMotto、userId、userHeadshot
     *  接口：/user/update/message
     *  请求类型post
     * @param userName
     * @param userSex
     * @param userBirth
     * @param userEmail
     * @param userTelephone
     * @param userMotto
     * @param userId
     * @param userHeadshot
     * @return
     */
    @RequestMapping(value ="/update/user/message",method = RequestMethod.POST)
    @ResponseBody
    public  JsonResult updateUserMessage(
            @RequestParam(value = "userName",defaultValue = "",required = false)String userName,
            @RequestParam(value = "userSex",defaultValue = "",required = false) String userSex,
            @RequestParam(value = "userBirth",defaultValue = "",required = false)String userBirth,
            @RequestParam(value = "userEmail",defaultValue = "",required = false) String userEmail,
            @RequestParam(value = "userTelephone",defaultValue = "",required = false)String userTelephone,
            @RequestParam(value = "userMotto",defaultValue = "",required = false) String userMotto,
            @RequestParam(value = "userId",defaultValue = "",required = false)String userId,
            @RequestParam(value = "userHeadshot",defaultValue = "",required = false)String userHeadshot
            ){
        User user=new User();
        user.setUserName(userName);
        user.setUserSex(userSex);
        user.setUserBirth(userBirth);
        user.setUserEmail(userEmail);
        user.setUserTelephone(userTelephone);
        user.setUserMotto(userMotto);
        user.setUserId(userId);
        user.setUserHeadshot(userHeadshot);
        JsonResult result=null;
        try{
            userService.updateUserMessage(user);
            System.out.println(userName);
            logger.info("参数:{}{}{}{}{}{}{}",userName,userSex,userBirth,userEmail,userTelephone,userMotto,userId);
            result=new JsonResult("查询成功","200");
        }catch (Exception ex){
            logger.info(ex.getMessage());
            result=new JsonResult("出错了","500");
        }
        return  result;
    }

    /**
     * 根据用户id查询用户粉丝数量@xyb
     * 接口/select/user/fansnumber
     * 传入参数userid
     * 请求类型post
     * 返回粉丝数量
     * @param userid
     * @return
     */
    @RequestMapping(value = "/select/user/fansnumber",method = RequestMethod.POST)
    @ResponseBody
    public  Object selectfans(
            @RequestParam(value = "userid",defaultValue = "",required = false)String userid
    ){
        JsonResult result=null;
        try {
            logger.info("参数{}",userid);
            Integer number=userService.selectfans(userid);
            result=new JsonResult("查询成功","200",number);
        }catch (Exception ex){
            logger.info(ex.getMessage());
            result=new JsonResult("出错了","500");
        }
        return result;
    }

    /**
     * 用户登录  (手机号,短信验证码)
     * 传入参数 userTelephone 用户手机号   code 验证码
     * 传出参数 User的所有字段
     * 接口 /user/login/by/code
     * @param code
     * @param userTelephone
     * @param request
     * @return
     */
    @RequestMapping("/user/login/By/Code")
    @ResponseBody
    public Object userLoginByCode(String code,String userTelephone, HttpServletRequest request){
        JsonResult result = null;
        //if(code.equals(String.valueOf(request.getSession().getAttribute("code")))){
            try{
                User user=userService.userLoginByCode(userTelephone);
                logger.info("传入参数：userTelephone:{}",userTelephone);
                if(user!=null){
                    result = new JsonResult("登录成功",Constant.STATUC_SUCCESS,user);
                    request.getSession().setAttribute("loginUser",user);
                    logger.info("Session存储：loginUser:{}", request.getSession().getAttribute("loginUser"));
                }else{
                    result = new JsonResult("用户名或密码错误",Constant.STATUC_UNFOUND);
                }
            }catch(Exception e){
                logger.info("错误信息：{}",e.getMessage());
                result = new JsonResult("登录异常",Constant.STATUC_FAILURE);
            }
      //  }
        return result;
    }
}
